var app=getApp()
var moduleUrl=app.baseUrl+'/client/event'
Page({
  data: {
    currentIndex:1,
    loading: true,
    isRefreshing: false,
    event_list: []
  },
  cancel(e) {
    var that = this
    dd.confirm({
      title: '操作确认',
      content: '是否取消报名',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      success({ confirm }) {
        if (confirm) {
          var id = e.target.dataset.id
          console.log(id)
          that.cancelApplyEventevent(id)
        }
      },
      fail() {
        console.log('fail');
      },
      complete() {
        console.log('complete');
        that.getUnBeginEvent()
      },
    });
  },
  signIn(e) {
    console.log('签到事件:', e)
    var that = this
    dd.prompt({
      title: '签到',
      message: '请输入签到码',
      inputType: 'text',
      buttonLabels: ["取消", "确认"],
      success(value) {
        console.log('prompt返回值:', value)
        if(value.buttonIndex==1) {
          console.log("用户点击确定")
          var id = e.target.dataset["id"]
          console.log('活动id:', id)
          var param = {
            eventId: id,
            userId: app.userId,
            code: value.value
          }
          that.postSignIn(param)
        } else {
          console.log("用户点击取消")
        }
      },
      complete() {
        console.log('模态框操作完成')
      }
    })
  },
  signOut(e) {
    console.log('签退事件:', e)
    var that = this
    dd.prompt({
      title: '签退',
      message: '请输入签退码',
      inputType: 'text',
      success(value) {
        console.log('prompt返回值:', value)
        if(value.buttonIndex==1) {
          console.log("用户点击确定")
          var id = e.target.dataset["id"]
          console.log('活动id:', id)
          var param = {
            eventId: id,
            userId: app.userId,
            code: value.value
          }
          that.postSignOut(param)
        } else {
          console.log("用户点击取消")
        }
      },
      complete() {
        console.log('模态框操作完成')
      }
    })
  },
  switchContent: function(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      currentIndex: index,
      loading: true,
      event_list: []
    });
    if(this.data.currentIndex==1){
      this.getUnBeginEvent()
    }else if(this.data.currentIndex==2){
      this.getUnSignInEvent()
    }
    else if(this.data.currentIndex==3){
      this.getUnSignOutEvent()
    }
    else if(this.data.currentIndex==4){
      console.log(this.data.event_list)
      this.getFinishedEvent()

    }
    console.log(this.data.currentIndex)
  },
  onLoad() {
    this.setData({
      baseUrl:app.baseUrl
    })
    console.log(this.data.event_list)
    this.getUnBeginEvent()
  },
  onShow() {
    console.log('===== 页面显示 =====');
    
    if (app.globalData && app.globalData.needRefreshEventList) {
      console.log('===== 需要刷新活动列表 =====');
      
      if(this.data.currentIndex === 1) {
        this.getUnBeginEvent();
      } else if(this.data.currentIndex === 2) {
        this.getUnSignInEvent();
      } else if(this.data.currentIndex === 3) {
        this.getUnSignOutEvent();
      } else if(this.data.currentIndex === 4) {
        this.getFinishedEvent();
      }
      
      app.globalData.needRefreshEventList = false;
    }
  },
  onHide() {
    console.log('===== 页面隐藏 =====');
  },
  onUnload() {
    console.log('===== 页面卸载 =====');
  },
  getUnBeginEvent(){
    var that = this
    
    this.setData({
      loading: true
    });
    
    dd.httpRequest({
      url: moduleUrl+'/unBeginEvent',
      method: 'GET',
      headers:{
        "Content-Type":"application/json"
      },
      data:{
        userId:app.userId,
      },
      success: function(res) {  
        that.setData({
          event_list:res.data.data,
          loading: false
        })
      },
      fail: function(res) {
        that.setData({
          loading: false
        });
        
        dd.showToast({
          type: 'fail',
          content: '数据加载失败，请重试',
          duration: 2000
        });
        
        if (app.handleError) {
          app.handleError(res, 'event页面');
        }
      },
      complete: function(res) {
        if (that.data.isRefreshing) {
          dd.stopPullDownRefresh();
        }
      }
    });
  },
  getUnSignInEvent(){
    var that = this
    
    this.setData({
      loading: true
    });
    
    dd.httpRequest({
      url: moduleUrl+'/unSignInEvent',
      method: 'GET',
      headers:{
        "Content-Type":"application/json"
      },
      data:{
        userId:app.userId
      },
      success: function(res) {  
        that.setData({
          event_list:res.data.data,
          loading: false
        })
      },
      fail: function(res) {
        that.setData({
          loading: false
        });
        
        dd.showToast({
          type: 'fail',
          content: '数据加载失败，请重试',
          duration: 2000
        });
        
        if (app.handleError) {
          app.handleError(res, 'event页面');
        }
      },
      complete: function(res) {
        if (that.data.isRefreshing) {
          dd.stopPullDownRefresh();
        }
      }
    });
  },
  getUnSignOutEvent(){
    var that = this
    console.log('getUnSignOutEvent:开始')
    
    this.setData({
      loading: true
    });
    
    dd.httpRequest({
      url: moduleUrl+'/unSignOutEvent',
      method: 'GET',
      headers:{
        "Content-Type":"application/json"
      },
      data:{
        userId:app.userId
      },
      success: function(res) {  
        that.setData({
          event_list:res.data.data,
          loading: false
        })
      },
      fail: function(res) {
        that.setData({
          loading: false
        });
        
        dd.showToast({
          type: 'fail',
          content: '数据加载失败，请重试',
          duration: 2000
        });
        
        if (app.handleError) {
          app.handleError(res, 'event页面');
        }
      },
      complete: function(res) {
        console.log(moduleUrl+'/unSignOutEvent',res);
        
        if (that.data.isRefreshing) {
          dd.stopPullDownRefresh();
        }
      }
    });
  },
  getFinishedEvent(){
    var that = this
    console.log('getFinishedEvent:开始')
    
    this.setData({
      loading: true
    });
    
    dd.httpRequest({
      url: moduleUrl+'/finishedEvent',
      method: 'GET',
      headers:{
        "Content-Type":"application/json"
      },
      data:{
        userId:app.userId
      },
      success: function(res) {  
        that.setData({
          event_list:res.data.data,
          loading: false
        })
      },
      fail: function(res) {
        that.setData({
          loading: false
        });
        
        dd.showToast({
          type: 'fail',
          content: '数据加载失败，请重试',
          duration: 2000
        });
        
        if (app.handleError) {
          app.handleError(res, 'event页面');
        }
      },
      complete: function(res) {
        console.log(moduleUrl+'/finishedEvent',res);
        
        if (that.data.isRefreshing) {
          dd.stopPullDownRefresh();
        }
      }
    });
  },
  cancelApplyEventevent(eventId){
    var that =this
    console.log("调用")
    //查出所有处于报名阶段的活动
      dd.httpRequest({
        url: moduleUrl+'/cancel',
        method: 'GET',
        data:{
          userId:app.userId,
          eventId:eventId
        },
        success: function(res) {  
          console.log(res.data)
          dd.showToast({
            type: 'success',
            content: '取消报名成功',
            duration: 2000
          })
        },
        fail: function(res) {
          // dd.alert({content: JSON.parse(res.originalData).rows'});
        },
        complete: function(res) {
          // dd.alert({content: 'complete'});
        }
      });
  },
  postSignIn(param) {
    const that = this
    
    dd.httpRequest({
      url: moduleUrl+'/signIn',
      method: 'GET', // 建议改为POST方法
      data: param,
      success: (res) => {
        dd.hideLoading()
        if(res.data.status === 200) {
          dd.showToast({
            type: 'success',
            content: '签到成功',
            duration: 2000
          })
          that.getUnSignInEvent()
        } else {
          dd.alert({ 
            title: '签到失败',
            content: res.data.message || '请检查签到码后重试'
          })
        }
      },
      fail: (res) => {
        dd.hideLoading()
        dd.alert({ 
          title: '网络异常',
          content: '请检查网络连接后重试'
        })
      }
    })
  },
  postSignOut(param){
    var that =this
    console.log('postSignOut:开始')
    //查出所有处于报名阶段的活动
      dd.httpRequest({
        url: moduleUrl+'/signOut',
        method: 'GET',
        data:param,
        success: function(res) {  
          var status=res.data.status
          if(status==200){
            dd.alert({
              title: '签退结果',
              content: res.data.data,
              buttonText: '确认',
              success: () => {
               that.getUnSignOutEvent()
              },
            });
          }else{
            dd.alert({
              title: '签退结果',
              content: res.data.message,
              buttonText: '确认',
              success: () => {
            
              },
            });
          }
        
        //  console.log("1231",that.data.event)
        },
        fail: function(res) {
          console.log("失败")
          // dd.alert({content: JSON.parse(res.originalData).rows'});
          dd.alert("签到码错误")
        },
        complete: function(res) {
          console.log(moduleUrl+'/signOut',res)
          that.getUnSignOutEvent()
        }
      });
  },
  statusText: function(status) {
    const map = {
      pending: '未开始',
      active: '进行中',
      completed: '已完成'
    }
    return map[status] || '未知状态'
  },
  navigateToDetail(e) {
    const id = e.currentTarget.dataset.id
    dd.navigateTo({
      url: `/pages/detail/detail?id=${id}`
    })
  },
  onPullDownRefresh() {
    console.log("===== 触发下拉刷新 =====");
    
    this.setData({
      isRefreshing: true
    });
    
    if(this.data.currentIndex === 1) {
      this.getUnBeginEvent();
    } else if(this.data.currentIndex === 2) {
      this.getUnSignInEvent();
    } else if(this.data.currentIndex === 3) {
      this.getUnSignOutEvent();
    } else if(this.data.currentIndex === 4) {
      this.getFinishedEvent();
    } else {
      dd.stopPullDownRefresh();
    }
  }
});
